
package com.eyedog.video.mine;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.eyedog.library.base.BaseFragment;
import com.eyedog.library.utils.DensityUtils;
import com.eyedog.video.R;
import com.eyedog.video.entity.CustomerEntity;
import com.eyedog.video.entity.ProfileEntity;
import com.eyedog.video.utils.DeviceUtil;
import com.eyedog.video.utils.ImageLoaderUtil;
import com.eyedog.video.utils.ImageUtils;
import com.eyedog.video.utils.KeyboardUtil;
import com.eyedog.video.utils.PathUtils;
import com.eyedog.video.utils.ToastUtil;
import com.eyedog.video.widgets.BasePopupWindow;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

/**
 * Created by thyme on 2019/7/21.
 */

public class MineFragment extends BaseFragment implements View.OnClickListener {
    private View service1, service2, service3;

    private TextView deviceIdTv, playCountTv, copyDeviceIdTv_, copyDeviceIdTv, refreshTv, copyUrl,
            generateQr, shareUrlTv, service1Tv, service2Tv, service3Tv, userDeviceId;

    private ProfileEntity profileEntity;

    private List<CustomerEntity> customerEntities;

    private String deviceId;

    private ViewPager mViewPager;

    private LinearLayout mLinearLayout;

    private List<ImageView> mImageList = new ArrayList<>();

    private int[] mPics = new int[] {
            R.drawable.page1, R.drawable.page2, R.drawable.page3
    };

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_mine, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable
    final Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        deviceIdTv = (TextView) view.findViewById(R.id.device_id);
        playCountTv = (TextView) view.findViewById(R.id.play_count);
        copyDeviceIdTv = (TextView) view.findViewById(R.id.copy_device_id);
        copyDeviceIdTv_ = (TextView) view.findViewById(R.id.copy_device_id_);
        refreshTv = (TextView) view.findViewById(R.id.refresh);
        copyUrl = (TextView) view.findViewById(R.id.copy_url);
        generateQr = (TextView) view.findViewById(R.id.generate_qr);
        shareUrlTv = (TextView) view.findViewById(R.id.share_url);
        userDeviceId = (TextView) view.findViewById(R.id.user_device_id);

        service1 = view.findViewById(R.id.customer_service1);
        service2 = view.findViewById(R.id.customer_service2);
        service3 = view.findViewById(R.id.customer_service3);
        service1.setOnClickListener(this);
        service2.setOnClickListener(this);
        service3.setOnClickListener(this);
        service1Tv = (TextView) view.findViewById(R.id.tv_service1);
        service2Tv = (TextView) view.findViewById(R.id.tv_service2);
        service3Tv = (TextView) view.findViewById(R.id.tv_service3);

        copyDeviceIdTv.setOnClickListener(this);
        copyDeviceIdTv_.setOnClickListener(this);
        refreshTv.setOnClickListener(this);
        copyUrl.setOnClickListener(this);
        generateQr.setOnClickListener(this);
        shareUrlTv.setOnClickListener(this);

        deviceId = DeviceUtil.getUniquePsuedoID();
        loadData();
    }

    private void loadData() {
        profileEntity = ProfileInstance.getInstance().getProfileEntity();
        if (profileEntity != null) {
            deviceIdTv.setText(deviceId);
            userDeviceId.setText(deviceId);
            shareUrlTv.setText(profileEntity.share_url);
            playCountTv.setText(profileEntity.times_watched + "");
        }
        customerEntities = ProfileInstance.getInstance().getCustomerEntities();
        if (customerEntities != null) {
            int i = 0;
            for (CustomerEntity customerEntity : customerEntities) {
                i++;
                switch (i) {
                    case 1:
                        refreshCustomerView(customerEntity, service1);
                        break;
                    case 2:
                        refreshCustomerView(customerEntity, service2);
                        break;
                    case 3:
                        refreshCustomerView(customerEntity, service3);
                        break;
                }
            }
        }
    }

    private void refreshCustomerView(CustomerEntity customerEntity, View serviceView) {
        serviceView.setVisibility(View.VISIBLE);
        serviceView.setTag(customerEntity);
        switch (serviceView.getId()) {
            case R.id.customer_service1:
                service1Tv.setText(customerEntity.name);
                break;
            case R.id.customer_service2:
                service2Tv.setText(customerEntity.name);
                break;
            case R.id.customer_service3:
                service3Tv.setText(customerEntity.name);
                break;
        }
    }

    /**
     * 二维码弹窗
     *
     * @param context
     * @param url
     */
    private void showQrPop(final Context context, final String url) {

        BasePopupWindow.builder(context)
                .contentView(
                        LayoutInflater.from(context).inflate(R.layout.layout_qr_pop, null, false))
                .isOutsideTouch(true).isHeightWrap(false).setAlpha(1f).isWidthWrap(false)
                .setOnBasePopupWindowInitListener(
                        new BasePopupWindow.OnBasePopupWindowInitListener() {
                            @Override
                            public void onPopupInitViewListener(View contentView,
                                    final PopupWindow popupWindow) {
                                mViewPager = (ViewPager) contentView
                                        .findViewById(R.id.main_viewpager);
                                mLinearLayout = (LinearLayout) contentView
                                        .findViewById(R.id.main_linear);
                                final Bitmap bitmap = QRCodeEncoder.syncEncodeQRCode(url, 250,
                                        Color.BLACK, ImageLoaderUtil.drawable2Bitmap(context
                                                .getResources().getDrawable(R.mipmap.ic_launcher)));
                                getData(bitmap);
                                final int[] mNum = {
                                        0
                                };
                                contentView.findViewById(R.id.img_back)
                                        .setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                popupWindow.dismiss();
                                            }
                                        });

                                contentView.findViewById(R.id.copy_url)
                                        .setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                KeyboardUtil.clip(getActivity(), url);
                                                ToastUtil.showShort("已复制");
                                                popupWindow.dismiss();
                                            }
                                        });

                                mLinearLayout.getChildAt(mNum[0]).setEnabled(true);
                                mViewPager.setOnPageChangeListener(
                                        new ViewPager.OnPageChangeListener() {
                                            @Override
                                            public void onPageScrolled(int position,
                                                    float positionOffset,
                                                    int positionOffsetPixels) {
                                                mLinearLayout.getChildAt(mNum[0]).setEnabled(false);
                                                mLinearLayout.getChildAt(position).setEnabled(true);
                                                mNum[0] = position;
                                            }

                                            @Override
                                            public void onPageSelected(int position) {

                                            }

                                            @Override
                                            public void onPageScrollStateChanged(int state) {

                                            }
                                        });

                                MyAdapter mAdapter = new MyAdapter();
                                mViewPager.setAdapter(mAdapter);

                                final TextView saveTv = (TextView) contentView
                                        .findViewById(R.id.saveTv);
                                saveTv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        ImageView cur = mImageList.get(mViewPager.getCurrentItem());
                                        cur.setDrawingCacheEnabled(true);
                                        Bitmap bitmap = Bitmap.createBitmap(cur.getDrawingCache());
                                        cur.setDrawingCacheEnabled(false);

                                        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                                        boolean isSave = ImageUtils.save(bitmap,
                                                PathUtils.getExternalDcimPath() + File.separator
                                                        + format.format(new Date()) + ".JPEG",
                                                Bitmap.CompressFormat.JPEG);
                                        if (isSave) {
                                            ToastUtil.showShort("已保存");
                                        } else {
                                            ToastUtil.showShort("保存失败");
                                            PermissionDialog permissionDialog = new PermissionDialog(
                                                    getActivity());
                                            permissionDialog.show();
                                        }
                                        popupWindow.dismiss();
                                    }
                                });

                            }
                        })
                .build().show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.customer_service1:
            case R.id.customer_service2:
            case R.id.customer_service3:
                CustomerEntity customerEntity = (CustomerEntity) v.getTag();
                if (customerEntity != null && !TextUtils.isEmpty(customerEntity.content)) {
                    Uri uri = Uri.parse(customerEntity.content);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
                break;
            case R.id.copy_device_id:
            case R.id.copy_device_id_:
                KeyboardUtil.clip(getActivity(), deviceId);
                ToastUtil.showShort("已复制");
                break;
            case R.id.copy_url:
                KeyboardUtil.clip(getActivity(),
                        profileEntity == null ? "" : profileEntity.share_url);
                ToastUtil.showShort("已复制");
                break;
            case R.id.refresh:
                loadData();
                ToastUtil.showShort("已刷新");
                break;
            case R.id.generate_qr:
                showQrPop(getActivity(), profileEntity == null ? "" : profileEntity.share_url);
                break;
        }

    }

    private void getData(Bitmap bitmap) {
        ImageView imageView;
        View view;
        for (int pic : mPics) {
            imageView = new ImageView(getActivity());
            imageView.setBackgroundResource(pic);
            imageView.setImageBitmap(bitmap);
            int dp30 = DensityUtils.dp2px(getActivity(), 70);
            imageView.setPadding(dp30, dp30, dp30, dp30);
            // 添加到数组
            mImageList.add(imageView);

            // 创建底部指示器(小圆点)
            view = new View(getActivity());
            view.setBackgroundResource(R.drawable.bg_pager_ind);
            view.setEnabled(false);
            // 设置宽高
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(16, 16);
            // 设置间隔
            if (pic != mPics[0]) {
                layoutParams.leftMargin = 15;
            }
            // 添加到LinearLayout
            mLinearLayout.addView(view, layoutParams);
        }
    }

    private class MyAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return mImageList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 获取图片view
            ImageView imageView = mImageList.get(position);
            // 设置到容器,也就是ViewPager
            container.addView(imageView);
            // 返回控件
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // 从容器中删除
            container.removeView(mImageList.get(position));
        }
    }

}
